package site.wlwsjsx.iot_backend.controller;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import site.wlwsjsx.iot_backend.dto.LabWorkstationStatsDTO;
import site.wlwsjsx.iot_backend.entity.LabInfo;
import site.wlwsjsx.iot_backend.entity.UserInfo;
import site.wlwsjsx.iot_backend.service.exception.ServiceException;
import site.wlwsjsx.iot_backend.service.LabInfoService;
import site.wlwsjsx.iot_backend.service.UserService;
import site.wlwsjsx.iot_backend.utils.JWTUtil;
import site.wlwsjsx.iot_backend.utils.JsonResultUtil;

import java.util.List;

/**
 * 实验室信息控制器
 */
@RestController
@RequestMapping("/lab")
public class LabInfoController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(LabInfoController.class);

    @Resource
    private LabInfoService labInfoService;

    @Resource
    private UserService userService;

    /**
     * 查询所有实验室信息
     */
    @GetMapping("/list")
    public JsonResultUtil<List<LabInfo>> getAllLabs() {
        log.info("查询所有实验室信息");
        JsonResultUtil<List<LabInfo>> result = new JsonResultUtil<>();

        List<LabInfo> labs = labInfoService.findAll();
        result.setState(OK);
        result.setMessage("查询成功");
        result.setData(labs);

        return result;
    }

    /**
     * 根据实验室ID查询实验室信息
     */
    @GetMapping("/{labId}")
    public JsonResultUtil<LabInfo> getLabById(@PathVariable Integer labId) {
        log.info("根据ID查询实验室信息 - labId: {}", labId);
        JsonResultUtil<LabInfo> result = new JsonResultUtil<>();

        LabInfo lab = labInfoService.findById(labId);
        if (lab != null) {
            result.setState(OK);
            result.setMessage("查询成功");
            result.setData(lab);
        } else {
            result.setState(404);
            result.setMessage("实验室不存在");
        }

        return result;
    }

    /**
     * 查询指定实验室的工位统计信息 - 需要管理员权限
     */
    @GetMapping("/{labId}/workstation-stats")
    public JsonResultUtil<LabWorkstationStatsDTO> getWorkstationStats(
            @PathVariable Integer labId,
            HttpServletRequest request) {
        log.info("开始查询实验室工位统计信息 - labId: {}", labId);
        JsonResultUtil<LabWorkstationStatsDTO> result = new JsonResultUtil<>();

        try {
            // 验证token
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                log.warn("查询工位统计信息失败：未提供认证令牌");
                return new JsonResultUtil<>(401, "未提供认证令牌", null);
            }

            // 验证token有效性
            DecodedJWT jwt = JWTUtil.verify(token);
            String username = jwt.getClaim("username").asString();
            String role = jwt.getClaim("role").asString();

            if (username == null) {
                log.warn("查询工位统计信息失败：无效的用户信息");
                return new JsonResultUtil<>(401, "无效的认证令牌", null);
            }

            // 验证用户是否存在
            UserInfo user = userService.findUserByUsername(username);
            if (user == null) {
                log.warn("查询工位统计信息失败：用户不存在");
                return new JsonResultUtil<>(401, "用户不存在", null);
            }

            // 执行查询
            LabWorkstationStatsDTO stats = labInfoService.getWorkstationStats(labId);
            if (stats == null) {
                log.warn("查询工位统计信息失败：实验室不存在，labId: {}", labId);
                result.setState(404);
                result.setMessage("实验室不存在");
            } else {
                log.info("成功查询工位统计信息，labId: {}, 用户: {}", labId, username);
                result.setState(200);
                result.setMessage("查询成功");
                result.setData(stats);
            }

        } catch (JWTVerificationException e) {
            log.error("JWT令牌验证异常: {}", e.getMessage());
            throw new ServiceException("无效的认证令牌", e);
        } catch (Exception e) {
            log.error("查询工位统计信息异常: {}", e.getMessage());
            throw new ServiceException("查询工位统计信息异常", e);
        }
        return result;
    }
}
